<script>
  let bg = document.getElementById("page-bg");
  bg.style.setProperty("will-change", "filter", "");
  let hue = 0;
  let isDark = document.documentElement.classList.contains("dark");

  // Listen for manual theme changes.
  document.addEventListener("hbThemeChange", (e) => {
    isDark = e.detail.isDarkTheme();
    console.debug("Theme changed manually - isDarkTheme? " + isDark);

    function sendMessage(message) {
      let iframe = document.querySelector("iframe.giscus-frame");

      if (!iframe) {
        return;
      }

      iframe.contentWindow.postMessage(
        { giscus: message },
        "https://giscus.app"
      );
    }

    sendMessage({
      setConfig: {
        theme: isDark ? "dark" : "light",
      },
    });
  });

  // Listen for system theme changes.
  window
    .matchMedia("(prefers-color-scheme: dark)")
    .addEventListener("change", ({ matches }) => {
      // Change background colour here for the system default mode only.
      if (
        "wc-color-theme" in localStorage ||
        window.hbb.defaultTheme !== "system"
      ) {
        return;
      }

      isDark = matches;
      console.debug("Theme changed by system - isDarkTheme? " + isDark);
    });

  setInterval(function () {
    hue = (hue + 1) % 360;

    if (isDark) {
      bg.style.setProperty(
        "filter",
        "hue-rotate(" + hue + "deg) invert(1) saturate(2)",
        ""
      );
    } else {
      bg.style.setProperty("filter", "hue-rotate(" + hue + "deg)", "");
    }
  }, 5000 / 360);
</script>
